package com.xcm.util;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * rest请求工具类
 */
public class RestClientUtils {
	public static final String SYSTEM_CHARSET = "UTF-8";
	
	public static final String SYSTEM_CHARSET_GBK ="GBK";
	
	private CloseableHttpClient httpclient = null;
	private Map<String, Object> param = new HashMap<String, Object>();
	private String targetUrl = null;

	private RestClientUtils(){}
	
	public static RestClientUtils newClient(){
		RestClientUtils restClient = new RestClientUtils();
		restClient.httpclient = HttpClientBuilder.create().build();
		return restClient;
	}
	
	public RestClientUtils target(String targetUrl){
		this.targetUrl = targetUrl;
		return this;
	}
	
	public RestClientUtils param(String key, Object value){
		param.put(key, value);
		return this;
	}
	
	/**
	 * @param remoteUrl 远程url
	 * @param paramMap 需要传递的参数
	 * args 
	 * */
	public static String post(String remoteUrl, Map<String, Object> paramMap, int ... args) {
		return post(remoteUrl, paramMap, SYSTEM_CHARSET);
	}
	
	/**
	 * post提交，支持String值、String[]值
	 * @param remoteUrl 访问地址
	 * @param paramMap  参数Map
	 * @param responseCharset   字符集
	 * @return  String
	 */
	public static String post(String remoteUrl, Map<String, Object> paramMap, String responseCharset) {
		try {
			//构建post
			HttpPost httpPost = new HttpPost(new URL(remoteUrl).toURI());
			//post参数
			if (paramMap != null && paramMap.size() > 0) {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				for (String key : paramMap.keySet()) {
					Object value = paramMap.get(key);
					if (value instanceof Object[]) {
						//数组值
						Object[] texts = (Object[])value;
						for (Object text : texts) {
							params.add(new BasicNameValuePair(key, text.toString()));
						}
					} else {
						String text = value.toString();
						params.add(new BasicNameValuePair(key, text));
					}
				}
				httpPost.setEntity(new UrlEncodedFormEntity(params, responseCharset));
			}
			//执行post
			CloseableHttpClient httpclient = HttpClientBuilder.create().build();
			HttpResponse response = httpclient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() != 200) {
				throw new RuntimeException("HTTP request Exception");
			}
			return EntityUtils.toString(response.getEntity(), responseCharset);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

}